package com.gaoqi.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import java.util.HashMap;
import java.util.Map;

/**
 * rabbitmq direct 配置
 */
@Configuration
public class DirectCommonConfiguration {
    public static final String exchangeName = "common_direct_exchange";
    public static final String queueName = "common_direct_queue";
    public static final String routeKey = "common";


    //声明注册direct 模式交换机
    @Bean("common_direct_exchange")
    public DirectExchange ttlDirectExchange() {
        return new DirectExchange(exchangeName, true, false);
    }

    //声明队列(具有过期时间)
    @Bean("common_direct_queue")
    public Queue ttlDirectQueue() {
        Map<String, Object> args = new HashMap<String, Object>();

        //设置队列有效时间
        args.put("x-message-ttl", 5000);

//        //设置队列每秒最大接收长度
//        args.put("x-max-length", 5);
//
        //与死信交换机关联
        args.put("x-dead-letter-exchange", DeadLetterConfiguration.exchangeName);
        args.put("x-dead-letter-routing-key", DeadLetterConfiguration.routeKey);
        //参数1: 队列名 参数2: 是否持久化  参数3: 队列是否独占 参数4: 是否自动删除  参数5: 额外参数
        return new Queue(queueName, true, false, false, args);
    }


    //交换机队列绑定(指定过期时间的队列)
    @Bean
    @DependsOn({
            "common_direct_exchange",
            "common_direct_queue"
    })
    public Binding ttl_directBinding(Exchange common_direct_exchange, Queue common_direct_queue) {
        //参数1: 绑定的队列名 参数2: 绑定交换机名 参数3: route key
        return BindingBuilder.bind(common_direct_queue).to(common_direct_exchange).with(routeKey).noargs();
    }
}
